#include "music.h"
#include <QMediaPlayer>
#include <QUuid>
#include <QCoreApplication>

Music::Music(const QUrl& url):
    isLike(false),
    isHistory(false),
    musicUrl(url)
{
    musicId = QUuid::createUuid().toString();
    // 加载歌曲文件
    parseMediaMetaData();
}

void Music::setIsLike(bool isLike)
{
    this->isLike = isLike;
}

void Music::setIsHistory(bool isHistory)
{
    this->isHistory = isHistory;
}

void Music::setMusicName(const QString &musicName)
{
    this->musicName = musicName;
}

void Music::setSingerName(const QString &singerName)
{
    this->singerName = singerName;
}

void Music::setAlbumName(const QString &albumName)
{
    this->albumName = albumName;
}

void Music::setDuration(const qint64 duration)
{
    this->duration = duration;
}

void Music::setMusicUrl(const QUrl &musicUrl)
{
    this->musicUrl = musicUrl;
}

void Music::setMusicId(const QString &musicId)
{
    this->musicId = musicId;
}

bool Music::getIsLike()
{
    return this->isLike;
}

bool Music::getIsHistory()
{
    return this->isHistory;
}

QString Music::getMucisName()
{
    return this->musicName;
}

QString Music::getSingerName()
{
    return this->singerName;
}

QString Music::getAlbumName()
{
    return this->albumName;
}

qint64 Music::getDuration()
{
    return this->duration;
}

QUrl Music::getMusicUrl()
{
    return this->musicUrl;
}

QString Music::getMusicId()
{
    return this->musicId;
}

void Music::parseMediaMetaData()
{
    // 解析是需要读取数据，读取数据需要用到QMediaPlayer类
    QMediaPlayer player;
    player.setMedia(musicUrl);
    // 媒体元素解析需要时间，只有等待解析完成，才能提取音乐信息，此处循环等待
    // 循环等待时：主界面消息循环就无法处理了，因此需要在等待解析期间，让消息循环继续处理
    while (!player.isMetaDataAvailable()) {
        QCoreApplication::processEvents();
    }

    // 解析媒体元素结束，提取元数据信息

    if(player.isMetaDataAvailable())
    {
        musicName = player.metaData("Title").toString();
        singerName = player.metaData("Author").toString();
        albumName = player.metaData("AlbumTitle").toString();
        duration = player.duration();

        QString fileName = musicUrl.fileName();
        int index = fileName.indexOf('-');
        if(musicName.isEmpty())
        {
            if(index != -1)
            {
                // "2002年的第⼀场雪 - ⼑郎.mp3"
                musicName = fileName.mid(0, index - 1).trimmed();
            }
            else
            {
                // "2002年的第⼀场雪.mp3"
                musicName = fileName.mid(0, fileName.indexOf('.')).trimmed();
            }
        }
        if(singerName.isEmpty())
        {
            if(index != -1)
            {
                singerName = fileName.mid(index + 1, fileName.indexOf('.') - index - 1).trimmed();
            }
            else
            {
                singerName = "未知歌手";
            }
        }
        if(albumName.isEmpty())
        {
            albumName = "专辑名未知";
        }
        qDebug() << musicName << " " << singerName << " " << albumName << " " << duration;
    }
}

